<template>
  <div >
    <div v-if="messageStatus">
        <n-card title="会员插件" header>
        <div class="header">
            <div>
            <NButton type="primary" @click="onClickAdd">
                添加会员
            </NButton>
            </div>
            <div>
            <n-input-group>
                <n-input v-model:value="params.keyword" clearable placeholder="请输入插件关键词" :style="{ width: '100%' }" />
                <n-button @click="List" type="primary" ghost>
                    搜索
                </n-button>
                </n-input-group>
            </div>
        </div>
        </n-card>
        <div class="box">
        <!-- 数据表 -->
        <div class="table-box">
            <div >
            <n-data-table
                striped 
                :loading="messageParams.loading"
                ref="table"
                :columns="columns"
                :data="data"
            />
            </div>
            <div class="pagination">
                <div>共{{pagination.total}}条数据</div>
                <div>
                <n-pagination
                v-model:page="params.pageNum"
                v-model:page-size="params.pageSize"
                :page-count="setPagination(pagination.total,params.pageSize )"
                show-size-picker
                :page-sizes="pageSizes"
                :on-update:page="pageNext"
                :on-update:page-size="sizeNext"
                />
                </div>
            </div>
        
        </div> 
            

        </div>
    </div>

    <div v-else class="Message">
        <n-result
            status="403"
            title="403 禁止访问"
            description="总有些门是对你关闭的"
        >
            <template #footer>
            <n-button @click="goTo('/pluginAdmin/all')">去充钱</n-button>
            </template>
        </n-result>
    </div>

   <n-modal  v-model:show="showModal"
        :mask-closable="false"
        preset="dialog"
        :title="popTitle"
        positive-text="确认"
        negative-text="算了"
        @positive-click="submitCallback"
        @negative-click="cancelCallback"
      >
      <div class="box-modal">
        
      </div>
  </n-modal>

  <yingModal  :title="popTitle" @close="cancelCallback" @confirm="submitCallback" :SkuShow="showModal" >
      <template #content>
        <n-form
          ref="formRef"
          :model="formValue"
          :rules="rules"
        >
          <n-form-item label="会员名称" path="title">
            <n-input v-model:value="formValue.title" placeholder="请输入会员名称" />
          </n-form-item>

          <n-form-item label="会员类型" path="title">
            <n-select v-model:value="formValue.type"
              :style="{ width: '400px' }" 
              filterable 
              placeholder="请选择会员类型"
              :options="Options"
              clearable
            />
          </n-form-item>



          <n-form-item label="会员LOGO" path="level_logo">
              <div @click="uploadShow=true" v-if="formValue.level_logo" style="height:135px;width:100px;overflow: hidden;display: flex;padding:12px;
                  justify-content: center; align-items: center;">
                  <n-image
                  :preview-disabled="true"
                  style="object-fit: contain;display: flex;
                      justify-content: center;
                      align-items: center;"
                  :src="Https()+formValue.level_logo"/>
              </div>
              <div v-else @click="uploadShow=true" class="imageUpload">
                <n-icon size="24" color="rgb(49, 108, 114)">
                  <svg xmlns="http://www.w3.org/2000/svg" xmlns:xlink="http://www.w3.org/1999/xlink" viewBox="0 0 16 16"><g fill="none"><path d="M8 2.5a.5.5 0 0 0-1 0V7H2.5a.5.5 0 0 0 0 1H7v4.5a.5.5 0 0 0 1 0V8h4.5a.5.5 0 0 0 0-1H8V2.5z" fill="currentColor"></path></g></svg>
                </n-icon>
              </div>
            </n-form-item>
         
            <n-form-item label="累计积分满多少分" v-if="formValue.type == '3'" path="level_score">
              <n-input v-model:value="formValue.level_score" placeholder="请输入累计积分满多少分" />
          </n-form-item>
          <n-form-item label="累计购买达多" v-if="formValue.type == '5'" path="level_order">
            <n-input v-model:value="formValue.level_order" placeholder="请输入累计购买达多" />
          </n-form-item>
          <n-form-item label="消费价格" v-if="formValue.type == '4' " path="level_money">
            <n-input v-model:value="formValue.level_money" placeholder="请输入累计消费满多少元" />
          </n-form-item>

          <n-form-item label="积累多少经验升级" v-if="formValue.type == '6'" path="level_experience">
            <n-input v-model:value="formValue.level_experience" placeholder="请输入积累多少经验升级" />
          </n-form-item>
          
          <n-form-item label="付费购买金额" v-if="formValue.type == '7' || formValue.type == '1' || formValue.type == '2'" path="level_payment">
            <n-input v-model:value="formValue.level_payment" placeholder="请输入付费购买金额" />
          </n-form-item>

           <n-form-item label="购买天数" v-if="formValue.type == '7' " path="level_payday">
            <n-input v-model:value="formValue.level_payday" placeholder="请输入购买天数" />
          </n-form-item>

          <n-form-item label="会员折扣" v-if="formValue.type == '2'" path="discount">
            <n-input v-model:value="formValue.discount" placeholder="请输入会员折扣" />
          </n-form-item>

          <n-form-item label="排序"  path="sort">
            <n-input v-model:value="formValue.sort" placeholder="请输入排序位置" />
          </n-form-item>

          <n-form-item label="状态">
            <n-switch v-model:value="formValue.status">
              <template #checked>
                启动
              </template>
              <template #unchecked>
                禁用
            </template>
            </n-switch>
          </n-form-item>
        </n-form>
      </template>
  </yingModal>

    

  <yingModal  :title="'文件管理'" @close="uploadShow=false" @confirm="uploadShow=false" :SkuShow="uploadShow" >
      <template #content>
        <Upload type="1" @selectImage="selectImageFun"/>
      </template>
  </yingModal>
  </div>
</template>

<script setup lang="ts">
import yingModal from "@/components/common/YingModal.vue"
import { NAvatar, NButton, NImage, NSwitch, NTag  } from 'naive-ui'
import type { FormInst } from 'naive-ui'
import { nextTick, onMounted, ref } from 'vue'
import { Https,setPagination } from "@/utils"
import api from './api'
import Upload from "@/views/upload/index.vue"
const router = useRouter()
const route = useRoute()
const pluginInfo = ref({})
const messageStatus = ref(false)
const uploadShow = ref(false)

const Options = ref([
  {
    label:'普通会员',
    value:'1'
  },
  {
    label:'plus会员',
    value:'2'
  },{
    label:'积分消费会员',
    value:'3'
  },{
    label:'价格消费会员',
    value:'4'
  }
  ,
  {
    label:'购买次数会员',
    value:'5'
  }
  ,{
    label:'经验会员',
    value:'6'
  },
  {
    label:'付费购买会员(权益卡)',
    value:'7'
  }

])
onMounted(() => {
     
    myPluin()
})


const selectImageFun =(selectImageList) =>{
   
  formValue.value.level_logo = selectImageList[0];  // 只获取第一张图
  uploadShow.value = false
} 

async function myPluin(){
  const res: any = await api.checkPluginApi({
    plugin_id:route.query.plugin_id,
    user_id:route.query.user_id,
  })
    
  if(res.code == 200 && res.data){
    pluginInfo.value = route.query
    params.value.user_id = route.query.user_id
    params.value.plugin_id = route.query.plugin_id
    messageStatus.value = true;
    List();
  }else{
    messageStatus.value = false;
  }

}

const pageSizes = [
  {
    label: '10 每页',
    value: 10
  },
  {
    label: '20 每页',
    value: 20
  },
  {
    label: '30 每页',
    value: 30
  },
  {
    label: '40 每页',
    value: 40
  }
]


const pagination = ref({
  total:10
  
})
const formRef = ref<FormInst | null>(null);

const showModal = ref(false);
const popTitle:any = ref('添加会员');
const params = ref({
  pageNum: 1,
  pageSize: 10,
  keyword: '',
  user_id:''
})

const formValue = ref({
  title:"",
  type:"",
  level_score:"",
  level_order:"",
  level_money:"",
  level_experience:"",
  level_payment:"",
  level_payday:"",
  level_logo:"",
  discount:"",
  sort:null,
  status:true,
})

const rules = {
    sort: {
        required: true,
        message: '请输入',
        trigger: 'blur'
    },
    title: {
        required: true,
        message: '请输入',
        trigger: 'blur'
    },
    type: {
        type: 'array',
        required: true,
        message: '请输入',
        trigger: 'blur'
    },
    level_score: {
        required: true,
        message: '请输入',
        trigger: 'blur'
    },
    level_order: {
        required: true,
        message: '请输入累计购买达多',
        trigger: 'blur'
    },
    level_money: {
        required: true,
        message: '请输入副标题',
        trigger: 'blur'
    },
    level_logo: {
        required: true,
        message: '请上传图片',
        trigger: 'blur'
    },
    level_payment: {
        required: true,
        message: '请输入',
        trigger: 'blur'
    },
    level_payday: {
        required: true,
        message: '请输入',
        trigger: 'blur'
    },
    discount: {
        required: true,
        message: '请输入',
        trigger: 'blur'
    },
     level_experience: {
        required: true,
        message: '请输入',
        trigger: 'blur'
    },
    
   
  
}

const columns = [
  {
    title: 'id',
    key: 'level_id',
    ellipsis: {
      tooltip: true
    }
 
  },
  {
    title: '会员名称',
    key: 'title',
    ellipsis: {
      tooltip: true
    }
 
  },
  {
    title: '会员类型',
    key: 'type',
    // width: 200,
    ellipsis: {
      tooltip: true
    },
    render: (item) => setType(item)
  },
  {
    title: '累计积分满多少分',
    key: 'level_score',
    // width: 200,
    ellipsis: {
      tooltip: true
    },
    
    
  },
 
  {
    title: '累计购买达多',
    key: 'level_order',
    // width: 200,
    ellipsis: {
      tooltip: true
    },
    
  },
   {
    title: '累计消费满多少元',
    key: 'level_money',
    // width: 200,
    ellipsis: {
      tooltip: true
    },
    
  },
  {
    title: '积累多少经验升级',
    key: 'level_experience',
    // width: 200,
    ellipsis: {
      tooltip: true
    },
    
  },
  {
    title: '付费购买金额',
    key: 'level_payment',
    // width: 200,
    ellipsis: {
      tooltip: true
    },
    
  },

  {
    title: '付费购买有效时间',
    key: 'level_payday',
    // width: 200,
    ellipsis: {
      tooltip: true
    },
    
  },
  {
    title: '折扣率',
    key: 'discount',
    // width: 200,
    ellipsis: {
      tooltip: true
    },
    
  },
  
  {
    title: '图片',
    
    ellipsis: {
      tooltip: true
    },
    render: (item) => h(NImage, {
            width: 60,
            src:Https() + item.level_logo || 'https://q6.itc.cn/q_70/images03/20240319/5567d75589bd46439af8e835beeac44f.png',
        })
    
  },
 
  
  {
    title: '状态',
    key: 'status',
    ellipsis: {
      tooltip: true
    },
    render: (item) => setStatus(item)
  },
  
  {
    title: '操作',
    key: 'actions',
    width: 360,
    align: 'right',
    fixed: 'right',
    hideInExcel: true,
  
    render(row) {
      return [
      
        h(
          NButton,
          {
            size: 'small',
            type: 'primary',
            style: 'margin-left: 12px;',
            secondary: true,
            onClick: () => handleOpenRolesSet(row),
          },
          {
            default: () => '编辑',
            icon: () => h('i', { class: 'i-fe:edit' }),
          },
        ),

        h(
          NButton,
          {
            size: 'small',
            type: 'error',
            style: 'margin-left: 12px;',
            onClick: () => handleDelete(row),
          },
          {
            default: () => '删除',
            icon: () => h('i', { class: 'i-material-symbols:delete-outline text-14' }),
          },
        ),
      ]
    },
  },

]

 
//  会员类型,1.普通会员 2.plus会员 3.积分消费会员 4.元子消费会员 5.购买次数会员 6.经验会员 7.付费购买会员
function setType(item){
    // console.log(item)
    if(item.type == "1")
      return '普通会员'
    else if(item.type == "2")
      return 'plus会员'
    else if(item.type == "3")
      return '积分消费会员'
    else if(item.type == "4")
      return '元子消费会员'
    else if(item.type == "5")
      return '购买次数会员'
    else if(item.type == "6")
      return '经验会员'
    else if(item.type == "7")
      return '付费购买会员(权益卡)'
    
}
 

function setStatus(item){
    // console.log(item)
    if(item.status)
        return h('span', { style: { color: 'green' } },'启用')
    else
        return h('span', { style: { color: 'red' } },'禁用')
}
const data: any = ref([])

async function handleDelete(item){
 
  const res: any = await api.DeleteApi({
    level_id:item.level_id,
    user_id:route.query.user_id
  })
  if(res.code == 200){
    List();
    $message.success('删除成功!')
  }else{
    
  }

}
const messageParams: any = ref({
  show: false,
  status: '403',
  loading: true,
})

const handleOpenRolesSet =(item) =>{
    formValue.value = item;
    formValue.value.sort = String(formValue.value.sort) 
    popTitle.value = '编辑';
    showModal.value = true;
} 

async function List() {
  try {
    messageParams.value.loading = true
    const res: any = await api.ListApi(params.value)
    if (res.code == 200) {
      messageParams.value.loading = false
      pagination.value.total = res.data.total
      data.value = res.data.list
      showModal.value = false;
    }
    else {
      messageParams.value.show = false
      messageParams.value.status = '500'
    }
  }
  catch (error) {
    console.error(error)
  }
}
function onClickAdd(){
  popTitle.value = '添加会员'
  showModal.value = true
  formValue.value = {
    title:"",
    type:null,
    level_score:"",
    level_order:"",
    level_money:"",
    level_experience:"",
    level_payment:"",
    level_payday:"",
    level_logo:"",
    discount:"",
    status:true,
  }
}
async function submitCallback() {
    messageParams.value.loading = true
    formRef.value?.validate((errors) => {
        if (!errors) {
        formValue.value.user_id = route.query.user_id
        formValue.value.plugin_id = route.query.plugin_id
        if(popTitle.value == '添加会员')
            AddFun();
        else
            EditFun();
        }
        else {
        showModal.value = true
        return 
    
        }
    })
}

async function AddFun(){
    
    const newData =  formValue.value
    newData.otherConfigJson = JSON.stringify(formValue.value.otherConfigJson)
    const res: any = await api.AddApi(newData)
    if(res.code == 200){
        List();
        $message.success('添加成功!')
    }else{
        $message.error(res.message)
    }
}

async function EditFun(){
  const res: any = await api.EditApi(formValue.value)
  if(res.code == 200){
    List();
    $message.success('编辑成功!')
  }else{
    $message.error(res.message)
  }
}

function pageNext(page){
  params.value.pageNum = page
  List();
}
function sizeNext(size){
    params.value.pageNum = 1
    params.value.pageSize = size
    List();
}


function cancelCallback() {
  List();
  showModal.value = false
}

function goTo(path){
    router.push(path)
}

function toStore(item){
    router.push({
      path:'/plugin/goodsPlugin/index',
      query:{
        user_id:route.query.user_id,
        store_id:item.businessId,
      }
    })
    // router.push('/plugin/goodsPlugin/index')
}
</script>

<style scoped>
 .box {
    /* height: 75vh; */
    overflow-y: auto;
}
.table-box{
  padding: 20px;
}
.box-modal{
  width: 410px;
  /* height: 550px; */
  
  overflow-y: auto;
}
.pagination{
  display: flex;
  justify-content: right;
  /* height: 60px; */
  gap: 10px;
  align-items: center;
  position: relative;
  top: 20px;
}
.header{
  display: flex;gap: 10px;
}
.Message{
    display: flex;
    align-items: center;
    justify-content: center;
    margin-top: 200px;
}
.imageUpload{
  width:100px;
  height:100px;
  border:1px solid #eee;
  display: flex;
  justify-content: center;
  border-radius: 6px;
  align-items: center;
}
.imageUpload:hover{
  border:1px solid rgb(49, 108, 114);
}
</style>
